﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace DataTransmissionDemo
{
    public class CheckAuthAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            bool checkAuth = false;
            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            if (controllerActionDescriptor != null)
            {
                checkAuth = controllerActionDescriptor.ControllerTypeInfo.IsDefined(typeof(CheckAuthAttribute), true);
                if (!checkAuth)
                {
                    //判断请求的方法有没有NoPermissionRequiredAttribute
                    checkAuth = controllerActionDescriptor.MethodInfo.IsDefined(typeof(CheckAuthAttribute), true);
                }
            }
            //需要权限
            if (checkAuth)
            {
                if (!context.HttpContext.Items.Keys.Contains("UserId"))
                    throw new HttpRequestException("未授权", new Exception(), System.Net.HttpStatusCode.Unauthorized);

            }

            base.OnActionExecuting(context);
        }
    }

    //public class CheckAuthFilter : IAsyncActionFilter
    //{
    //    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    //    {
    //        var checkAuth = context.Controller.
    //    }
    //}
}
